import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:jetour_line/aha_jetour_line.dart';
import 'package:jetour_line/models/public_msg_manger.dart';
import '../utils/aha_utils.dart';
import '../utils/crypto_util.dart';

class AhaRouter {
  //路书列表
  static const String lineList = "/v3/applets/line/line-list";

  /// 路书详情
  static const String LineLinedetail = "/v3/applets/line/line-detail"; //路书详情
  static const String MyJetourTokenLogin =
      "/v3/applets/my/jetour/token-login"; // - 捷途登陆
  static const String LineToolPoiList =
      "/v3/applets/line-tool/poi-list"; //搜索阿哈POI -酒店|景区
  static const String LineToolPoiInAmap =
      "/v3/applets/line-tool/poi-in-amap"; //搜索阿哈POI -餐饮|其他(高德)
  static const String MyCollectOne = "/v3/mapi/my/collect_one"; //收藏接口：路书、活动等等
  static const String MyCollectList = "/v3/mapi/my/collect_list"; //收藏列表
  static const String MyOrderList = "/v3/mapi/order/list"; //订单列表
  static const String MyOrderDelete = "/v3/mapi/order/delete"; //删除订单
  static const String MyOrderDetail = "/v3/mapi/order/line/detail"; //路书订单详情
  static const String CityList = "/v3/applets/city/city-list"; //城市列表 - 阿哈
  static const String LineCreatOrder = "/v3/mapi/line/create_order"; //购买路书
  static const String MineTrankList = "/v3/mapi/track/list"; //我的轨迹
  static const String MineTrankDelete = "/v3/mapi/track/delete"; //删除轨迹
  static const String MineTrankDetail = "/v3/mapi/track/detail"; //轨迹详情
  static const String ThemeList = "/v3/applets/line/theme-list"; //路书主题列表
  static const String CityRegeo = "/v3/applets/city/city-regeo"; //逆地理编码 - 阿哈
  static const String JoinByCode = "/v3/applets/group-trip/join-by-code"; //通过邀请码加入队伍
}

class _HttpConfig {
  static const int timeout = 20000;
  static const String appId = "1669687766";
  static const String appSecret = "42967910268c1e3609c6eb4b4d67bd66";
  static const String publicKey =
      "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK//smpd9HTfqV95z5tJBE5L60PDt9Ou\n8CvFovKZ96sBNVfNxm2+22Ew79+bv0Cw7qEmqUGH9oDKHSc8CTc0bL8CAwEAAQ==\n-----END PUBLIC KEY-----";
}

class AhaHttp {
  late final Dio dio;
  AhaHttp._internal() {
    String baseUrl = "https://restapi.ahatrip.net";
    if (kReleaseMode) {
      if (AhaManger().isUat) {
        baseUrl = 'http://devrestapi.ahatrip.net';
      } else {
        baseUrl = "https://restapi.ahatrip.net";
      }
      // baseUrl = "https://restapi.ahatrip.net";
    } else {
      if (AhaManger().isUat) {
        baseUrl = 'http://devrestapi.ahatrip.net';
      } else {
        baseUrl = "https://restapi.ahatrip.net";
      }
    }
    final config =
        BaseOptions(baseUrl: baseUrl, connectTimeout: _HttpConfig.timeout);
    dio = Dio(config);
    Interceptor commonInterceptor = InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
      String date = DateTime.now().millisecondsSinceEpoch.toString();
      date = date.substring(0, date.length - 3);
      String crypto = _HttpConfig.appId + _HttpConfig.appSecret + date;
      // todo token
      options.headers.addAll({
        "t": date,
        "sign": CryptoUtil.string2Md5(crypto),
        'appId': _HttpConfig.appId
      });
      if (PublicMsgManger().userInfoModel != null) {
        options.headers.addAll({
          "token": PublicMsgManger().userInfoModel!.token,
        });
      }
      handler.next(options);
    }, onResponse:
            (Response response, ResponseInterceptorHandler handler) async {
              // print('responseresponseresponse${response.data}');
              Map<dynamic, dynamic> dataMap = response.data;
      if (dataMap['code'] == 0) {
        return handler.next(response);
      }  else if (dataMap["code"] == 9999) {
        // Utils.showToast('您的账户已在其它设备登录，请重新登录');
        // LoginUtil.outLogin();
        // eventBus.fire(ChangeUserInfo());
        //

        //阿哈从新登陆，获取jetourtoken，获取阿哈token

        //重新请求
        // Response<dynamic> newResponse = await get(response.requestOptions.path,
        //     params: response.requestOptions.queryParameters,
        //     context: response.requestOptions.extra['context'],
        //     headers: response.requestOptions.headers);

        // return handler.next(newResponse);
        return handler.reject(dataMap['msg']);
      } else {
        String msg = dataMap['msg'];
        if(!msg.contains('http')&& !msg.contains('error')){
          AhaUtils.showTxt(msg);
        }
        return handler.reject(dataMap['msg']);
      }
    });
    dio.interceptors.add(commonInterceptor);
  }

  static final _instance = AhaHttp._internal();

  factory AhaHttp() => _instance;

  Future get(url,
      {Map<String, dynamic>? params,
      BuildContext? context,
      Map<String, dynamic>? headers }) async {

    final options = Options(headers: headers, extra: {'context': context});
    try {
      Response<dynamic> response =
          await dio.get(url, queryParameters: params, options: options);
      Map<dynamic, dynamic> dataMap = response.data;
      return dataMap["data"];
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }

  Future post(url,
      {Map<String, dynamic>? params,
      Map<String, dynamic>? data,
      BuildContext? context,
      Map<String, dynamic>? headers}) async {
    final options = Options(headers: headers, extra: {'context': context});
    try {
      Response<dynamic> response = await dio.post(url,
          queryParameters: params, data: data, options: options);
      Map<dynamic, dynamic> dataMap = response.data;
      return dataMap["data"];
    } on DioError catch (e) {
      return Future.error(e.message);
    }
  }
}
